using System.Collections;
using System.Collections.Generic;
using Game.Framework.FState;
using Game.Framework.Utils;
using UnityEngine;
using YooAsset;

namespace Game.Framework
{
    public class StateYooAssetDownloader : StateYooAssetBase
    {
        public override void Enter(StateData param)
        {
            base.Enter(param);
            YooAssetManager.Instance.StartCoroutine(Downloader());
        }
        
        public override void FixedUpdate(float deltaTime)
        {
            base.FixedUpdate(deltaTime);
        }
        
        public override void Update()
        {
            base.Update();
        }
        
        public override void Exit()
        {
            base.Exit();
        }

        private IEnumerator Downloader()
        {
            yield return new WaitForSecondsRealtime(0.5f);
            int downloadingMaxNum = 10;
            int failedTryAgain = 3;
            var package = YooAssets.GetPackage(AssetConfig.Instance.PackageName);
            var downloader = package.CreateResourceDownloader(downloadingMaxNum, failedTryAgain);
            if (downloader.TotalDownloadCount == 0)
            {
                EventBus.Send<EventNoAssetNeedDownLoad>();
                yield break;
            }
            
            //注册回调方法
            downloader.OnDownloadErrorCallback = OnDownloadErrorCallback;
            downloader.OnDownloadProgressCallback = OnDownloadProgressCallback;
            downloader.OnDownloadOverCallback = OnDownloadOverCallback;
            downloader.OnStartDownloadFileCallback = OnStartDownloadFileCallback;
            
            //开启下载
            downloader.BeginDownload();
            yield return downloader;
        }
        
        private void OnDownloadErrorCallback(string fileName, string error)
        {
            EventBus.Send(new EventAssetDownError(fileName,error));
        }
        private void OnDownloadProgressCallback(int totalDownloadCount, int currentDownloadCount, long totalDownloadBytes, long currentDownloadBytes)
        {
            EventBus.Send(new EventAssetDownloadProgress(totalDownloadCount,currentDownloadCount,totalDownloadBytes,currentDownloadBytes));
            LogUtil.Log("Count = {0}/{1} | DownloadProgress = {2}/{3}",totalDownloadCount,currentDownloadCount,currentDownloadBytes,totalDownloadBytes);
        }
        private void OnDownloadOverCallback(bool isSucceed)
        {
            EventBus.Send(new EventAssetDownDone(isSucceed));
            ChangeState<StateYooAssetUpdaterDone>(null);
        }
        private void OnStartDownloadFileCallback(string fileName, long sizeBytes)
        {
            
        }
    }
}


